package test1;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

//德鲁伊连接池的连接及断开
public class JDBCUtil {
    //创建Datasource对象
    private static DataSource ds;
    static {
        //创建Properties对象
        Properties pro = new Properties();
        try {
            pro.load(JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            ds= DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 返回链接对象
     */
    public static Connection getconnection() throws SQLException {
        return ds.getConnection();
    }
    /**
     * 关闭流
     */
    public static void close(Statement sta, Connection con){
        if(sta != null){
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con !=null){
            try {
                con.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 关闭三个流
     */
    public static void close(ResultSet rs, Statement sta, Connection con){
        if(rs !=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(sta !=null){
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(con !=null){
            try {
                con.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 获取数据源
     */
    public static DataSource getDatasource(){
        return ds;
    }

}
